<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-11-04 10:37:34
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-07-06 13:54:53
-->
<template>
  <j-modal
    :visible.sync="modal.visible"
    :width="1200"
    :title="modal.title"
    :fullscreen.sync="modal.fullscreen"
    :switchFullscreen="modal.switchFullscreen"
    @cancelVisible="cancel"
  >
    <template>
      <div class="form-wrap">
        <a-row :gutter="[48, 8]">
          <a-col :span="6"><span class="title">角色编号：</span>{{ roleInfo.roleCode }}</a-col>
          <a-col :span="6"><span class="title">角色名称：</span>{{ roleInfo.roleName }}</a-col>
        </a-row>
        <div></div>
        <a-row :gutter="[8, 8]">
          <a-col :span="25">
            <a-card :loading="tableLoading" :bordered="false">
              <a-tabs :default-active-key="activeKey" @change="callback">
                <a-tab-pane :key="`${i + 1}`" :tab="pitem.title" v-for="(pitem, i) in dataList">
                  <a-table
                    bordered
                    :columns="columns"
                    :data-source="pitem.children"
                    size="middle"
                    childrenColumnName="ppp"
                    :pagination="false"
                    :scroll="{ x: 800, y: 'calc(100vh - 330px)' }"
                    class="j-table-force-nowrap"
                  >
                    <!-- 模块 -->
                    <span slot="slotTitle" slot-scope="text, record, index" v-if="!record.hidden || record.url == '/account'">
                      <a-checkbox :checked="record.checked" @change="(e) => oneChecked(record, index)"
                        >{{ text }}
                      </a-checkbox>
                    </span>
                    <!-- 页面 -->
                    <div slot="children" slot-scope="text, record, indexs" v-if="record.children">
                      <div
                        v-for="(twoItem, twoIndex) in record.children"
                        :key="twoItem.key"
                        class="children-box flexBox"
                        :style="{ height: boxHeight(twoItem) }"
                      >
                        <a-checkbox
                          :disabled="!record.checked"
                          :checked="twoItem.checked"
                          @change="(e) => twoChecked(twoItem, indexs, twoIndex)"
                          :style="twoHeight(twoItem)"
                          >{{ twoItem.title }}
                        </a-checkbox>
                      </div>
                    </div>
                    <!-- 按钮 -->
                    <div slot="threeChildren" slot-scope="text, record, index" v-if="record.children">
                      <div
                        v-for="(twoItem, twoIndex) in record.children"
                        :key="twoItem.key"
                        class="children-box"
                        :style="{ height: boxHeight(twoItem) }"
                      >
                        <div class="columnFlexBtn">
                          <span
                            v-for="(threeItem, threeIndex) in twoItem.children"
                            :key="threeItem.key"
                            v-show="!threeItem.hidden"
                          >
                            <a-checkbox
                              :checked="threeItem.checked"
                              @change="(e) => treeChecked(threeItem, index, twoIndex, threeIndex)"
                            >
                              {{ threeItem.title }}
                            </a-checkbox>
                          </span>
                        </div>
                      </div>
                    </div>
                    <!-- 数据权限 -->
                    <div slot="dataRoles" slot-scope="text, record" v-if="record.children">
                      <div
                        v-for="item in record.children"
                        :key="item.sid"
                        :style="goDataHeights(item)"
                        class="children-box"
                      >
                        <div style="padding-left: 16px">
                          <a-radio-group
                            @change="(e) => changeRadio(item)"
                            :disabled="!item.checked || (item.permRuleList && item.permRuleList.length === 1)"
                            v-model="item.dataRuleIds"
                            size="small"
                          >
                            <a-radio
                              v-for="(items, index) in item.permRuleList"
                              :key="index"
                              :style="radioStyle"
                              :value="items.id"
                            >
                              {{ items.ruleName }}
                            </a-radio>
                          </a-radio-group>
                        </div>
                      </div>
                    </div>
                  </a-table>
                </a-tab-pane>
              </a-tabs>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </template>
    <template slot="footer">
      <a-button key="back" @click="cancel"> 取消 </a-button>
      <a-button key="submit" :disabled="tableLoading" type="primary" @click="submit" :loading="loadingForm"> 确定 </a-button>
    </template>
  </j-modal>
</template>

<script>
import { validateCheckCode, getList } from '@/utils/util'
import { getAction, postAction, putAction } from '@/api/manage'
export default {
  name: 'formPage',
  components: {},
  data() {
    return {
      validateCheckCode,
      modal: {
        title: '角色授权',
        visible: false,
        fullscreen: false,
        switchFullscreen: true,
      },
      loadingForm: false,
      roleInfo: {},
      dataList: [],
      activeKey: '1',
      tableLoading: false,
      columns: [
        {
          title: '模块',
          key: '1',
          dataIndex: 'title',
          width: '15%',
          scopedSlots: { customRender: 'slotTitle' },
        },
        {
          title: '页面',
          key: '2',
          dataIndex: 'id',
          width: '15%',
          scopedSlots: { customRender: 'children' },
        },
        {
          title: '按钮',
          key: '6',
          dataIndex: 'value',
          width: '30%',
          scopedSlots: { customRender: 'threeChildren' },
        },
        {
          title: '数据权限',
          // width: 200,
          key: '3',
          scopedSlots: { customRender: 'dataRoles' },
        },
      ],
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      data: [],
      dataRuleIds: [],
      queryId: '',
      sysRolePermissionList: [],
      dataListIndex: 0
    }
  },
  methods: {
    changeRadio(v) {
      this.$forceUpdate()
    },
    callback(i) {
      this.dataListIndex = i - 1
      // this.setDataSource(this.dataList[i - 1].children)
    },
    setDataSource(modalTree) {
      // this.dataList[dataListIndex].children = modalTree
      let arr = []
      if (this.sysRolePermissionList.length > 0) {
        let setTree = (list) => {
          for (let i = 0; i < list.length; i++) {
            const tree = list[i]
            let has = this.sysRolePermissionList.find((v) => v.permissionId == tree.id)
            
            if (has) {
              // tree.checked = true
              this.$set(tree, 'checked', true)
              console.log('有选中的了贷记卡是男的就卡死');
              tree.dataRuleIds = has.dataRuleIds
              if (tree.permRuleList&&tree.permRuleList.length==1) {
                tree.dataRuleIds = tree.permRuleList[0].id
              }
            } else {
              // tree.checked = false
              this.$set(tree, 'checked', false)
            }
            if (tree.children && tree.children.length > 0) {
              setTree(tree.children)
            }
          }
        }
        for (let j = 0; j < modalTree.length; j++) {
          const data = modalTree[j];
          setTree(data.children)
        }
      }
      this.dataList = modalTree
    },
    // 新增表单
    open(obj) {
      this.roleInfo = obj
      this.dataList = []
      this.modal.visible = true
      this.tableLoading = true
      getAction('/sys/permission/queryByRoleId', { roleId: obj.id })
        .then(res => {
          if (res.code == 200) {
          this.sysRolePermissionList = res.result.sysRolePermissionList || []
          this.getList()
          this.queryId = res.result.id
        }
        })
    },
    getList() {
      getAction('/sys/permission/empowerment', {tenantId: this.$store.getters.tenantid}).then((res) => {
        if (res.code == 200) {
          // this.dataList = res.result
          if (res.result&&res.result.length > 0) {
            this.setDataSource(res.result)
            // for (let i = 0; i < this.dataList.length; i++) {
            //   const item = this.dataList[i];
            //   this.setDataSource(item.children)
            // }
          }
        } else {
          this.$antdMessage(res.message)
        }
      })
        .finally(() => {this.tableLoading = false})
    },
    // 提交表单
    submit() {
      this.loadingForm = true
      let params = {
        id: this.roleInfo.id,
        sysRolePermissionList: []
      }
      let fun = (list) => {
        for (let i = 0; i < list.length; i++) {
          const tree = list[i]
          let arr1 = [],
              arr2 = []
          if (tree.checked) {
            arr1.push(tree.id)
            if (tree.dataRuleIds) {
              arr2.push(tree.dataRuleIds)
            }
            params.sysRolePermissionList.push({
              permissionId: arr1.join(','),
              dataRuleIds: arr2.join(','),
            })
          }
          if (tree.children && tree.children.length > 0) {
            fun(tree.children)
          }
        }
      }
      for (let j = 0; j < this.dataList.length; j++) {
        const data = this.dataList[j];
      fun(data.children)
        
      }
      // params.tenantId = this.$store.getters.tenantid
      postAction('/sys/role/editRolePermissions', params)
        .then((res) => {
          if (res.success) {
            this.$antdMessage.success(res.message)
            this.cancel()
          } else {
            this.$antdMessage.error(res.message)
          }
          this.loadingForm = false
        })
        .catch((err) => {
          this.loadingForm = false
        })
    },
    // 关闭表单
    cancel() {
      this.loadingForm = false
      this.modal.visible = false
    },
    oneChecked(r, i) {
      this.dataList[this.dataListIndex].children[i].checked = !r.checked
      if (this.dataList[this.dataListIndex].children[i].children) {
        for (let j = 0; j < this.dataList[this.dataListIndex].children[i].children.length; j++) {
          const item = this.dataList[this.dataListIndex].children[i].children[j]
          item.checked = !this.dataList[this.dataListIndex].children[i].checked
          this.twoChecked(item, i, j)
        }
      }
      this.$forceUpdate()
    },
    twoChecked(r, i, k) {
      this.dataList[this.dataListIndex].children[i].children[k].checked = !r.checked
      if (this.dataList[this.dataListIndex].children[i].children[k].children) {
        for (let j = 0; j < this.dataList[this.dataListIndex].children[i].children[k].children.length; j++) {
          const item = this.dataList[this.dataListIndex].children[i].children[k].children[j]
          item.checked = this.dataList[this.dataListIndex].children[i].children[k].checked
        }
      }
      if (r.permRuleList && r.permRuleList.length > 0 && r.checked) {
        this.dataList[this.dataListIndex].children[i].children[k].dataRuleIds = JSON.parse(JSON.stringify(r.permRuleList[r.permRuleList.length - 1].id))
      } else {
        this.dataList[this.dataListIndex].children[i].children[k].dataRuleIds = ''
      }
      if (r.permRuleList && r.permRuleList.length === 1 && !r.checked) {
        this.dataList[this.dataListIndex].children[i].children[k].dataRuleIds = null
      }
      this.$forceUpdate()
    },
    treeChecked(r, i, j, k) {
      this.dataList[this.dataListIndex].children[i].children[j].children[k].checked = !r.checked
      this.$forceUpdate()
    },
    boxHeight(twoItem) {
      let heightNum = 135
      // if (twoItem.children && twoItem.children.length > 0) {
      //   heightNum = 135 * twoItem.children.length
      // } else {
      //   heightNum = 135
      // }
      return heightNum + 'px'
    },
    twoHeight(twoItem) {
      if (!twoItem.children) {
        return ''
      }
      if (twoItem.children && twoItem.children.length >= 5) {
        return `height:${twoItem.children.length * 25 + 25}px;line-height: ${
          twoItem.children.length > 0 ? twoItem.children.length * 25 + 25 : 25
        }px;`
      } else {
        return `height:${twoItem.children.length * 40 + 40}px;line-height: ${
          twoItem.children.length > 0 ? twoItem.children.length * 40 + 40 : 40
        }px;`
      }
    },
    goDataHeights(item) {
      if (item.children && item.children.length == 0) {
        if (item.children.length >= 5) {
          return `height:${item.children.length * 25 + 25}px;line-height: 56px;`
        } else {
          return `height:${item.children.length * 40 + 40}px;padding: 15px 0;`
        }
      }
    },
    getDataHigh(item) {
      if (item.children && item.children.length == 0) {
        return `line-height: 56px;height:135px`
      } else {
        return `padding: 15px 0;height:135px`
      }
    },
  },
}
</script>

<style lang="less" scoped>
/deep/.ant-modal-body {
  padding: 12px !important;
  .ant-form-item {
    margin-bottom: 0;
  }
}
/deep/.ant-card-body {
  padding: 0;
}
.form-wrap {
  background: #fff;
  height: 100%;
  padding: 24px;
  overflow-y: scroll;
  .code-btn {
    position: absolute;
    right: 0;
    top: -50.5px;
  }
}
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}
.title {
  font-size: 16px;
  color: #191f25;
}

/deep/.ant-table-body {
  overflow-x: hidden !important;
}
.children-box {
  margin: 0 -8px;
  min-height: 135px;
  // line-height: 30px;
  border-bottom: 1px solid #e8e8e8;
  // border-bottom: 1px solid red;
}

.children-box:last-child {
  // margin:0px -16px;
  // height: 50px;
  // line-height: 30px;
  border-bottom: none;
}
.children-boxs {
  line-height: 30px;
  // border-bottom: 1px solid #fff;
}
.main-box {
  display: flex;
  flex-flow: row nowrap;
  .left-box {
    width: 320px;
    overflow: scroll;
    height: calc(100vh - 75px);
    .ant-menu-item-selected {
      display: flex;
      justify-content: space-between;
      background: #d2e9ff;
    }
  }
  .right-box {
    margin-left: 20px;
    flex: 1;
    overflow: scroll;
    height: calc(100vh - 75px);
  }
}
.flexBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-left: 16px;
  box-sizing: border-box;
}
.columnFlexBox {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  flex-direction: column;
  padding: 16px;
  box-sizing: border-box;
  overflow-y: auto;
}
.columnFlexBtn {
  display: flex;
  padding: 16px;
  box-sizing: border-box;
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: space-between;
  height: 100%;
  span {
    margin: 0 10px;
    display: inline;
  }
}
/deep/ .j-table-force-nowrap td {
  white-space: inherit;
}
</style>
